package com.bcu.cn.onlineexamsystem.grademanage.service.impl;

import com.bcu.cn.onlineexamsystem.grademanage.entity.TeacherScoreAnalysisDTO;
import com.bcu.cn.onlineexamsystem.grademanage.mapper.TeacherScoreAnalysisMapper;
import com.bcu.cn.onlineexamsystem.grademanage.service.TeacherScoreAnalysisService;
import com.bcu.cn.onlineexamsystem.studentmanage.util.DataTypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 教师端成绩分析服务实现类
 */
@Service
public class TeacherScoreAnalysisServiceImpl implements TeacherScoreAnalysisService {
    
    private static final Logger logger = LoggerFactory.getLogger(TeacherScoreAnalysisServiceImpl.class);
    
    @Autowired
    private TeacherScoreAnalysisMapper teacherScoreAnalysisMapper;
    
    @Override
    public TeacherScoreAnalysisDTO.ScoreStatistics getScoreStatistics() {
        logger.info("=== 获取教师端成绩统计数据 ===");
        
        try {
            Map<String, Object> result = teacherScoreAnalysisMapper.getScoreStatistics();
            logger.info("数据库查询结果: {}", result);
            
            if (result == null) {
                logger.warn("未查询到统计数据");
                return createEmptyStatistics();
            }
            
            TeacherScoreAnalysisDTO.ScoreStatistics statistics = new TeacherScoreAnalysisDTO.ScoreStatistics();
            statistics.setTotalStudents(DataTypeConverter.toInteger(result.get("totalStudents")));
            statistics.setTotalExams(DataTypeConverter.toInteger(result.get("totalExams")));
            statistics.setAverageScore(DataTypeConverter.toBigDecimal(result.get("averageScore")));
            statistics.setHighestScore(DataTypeConverter.toBigDecimal(result.get("highestScore")));
            statistics.setLowestScore(DataTypeConverter.toBigDecimal(result.get("lowestScore")));
            statistics.setPassCount(DataTypeConverter.toInteger(result.get("passCount")));
            statistics.setFailCount(DataTypeConverter.toInteger(result.get("failCount")));
            statistics.setPassRate(DataTypeConverter.toBigDecimal(result.get("passRate")));
            
            logger.info("转换后的统计数据: {}", statistics);
            return statistics;
        } catch (Exception e) {
            logger.error("获取成绩统计数据失败", e);
            return createEmptyStatistics();
        }
    }
    
    @Override
    public TeacherScoreAnalysisDTO.ScoreTrend getScoreTrend() {
        logger.info("=== 获取教师端成绩趋势数据 ===");
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getScoreTrend();
            logger.info("数据库查询结果: {}", result);
            
            TeacherScoreAnalysisDTO.ScoreTrend trend = new TeacherScoreAnalysisDTO.ScoreTrend();
            List<String> examDates = new ArrayList<>();
            List<BigDecimal> averageScores = new ArrayList<>();
            List<String> examNames = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    examDates.add(DataTypeConverter.toString(row.get("examDate")));
                    averageScores.add(DataTypeConverter.toBigDecimal(row.get("averageScore")));
                    examNames.add(DataTypeConverter.toString(row.get("examName")));
                }
            }
            
            trend.setExamDates(examDates);
            trend.setAverageScores(averageScores);
            trend.setExamNames(examNames);
            
            logger.info("转换后的趋势数据: {}", trend);
            return trend;
        } catch (Exception e) {
            logger.error("获取成绩趋势数据失败", e);
            return new TeacherScoreAnalysisDTO.ScoreTrend();
        }
    }
    
    @Override
    public TeacherScoreAnalysisDTO.ScoreDistribution getScoreDistribution() {
        logger.info("=== 获取教师端成绩分布数据 ===");
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getScoreDistribution();
            logger.info("数据库查询结果: {}", result);
            
            TeacherScoreAnalysisDTO.ScoreDistribution distribution = new TeacherScoreAnalysisDTO.ScoreDistribution();
            List<String> ranges = new ArrayList<>();
            List<Integer> counts = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    ranges.add(DataTypeConverter.toString(row.get("scoreRange")));
                    counts.add(DataTypeConverter.toInteger(row.get("count")));
                }
            }
            
            distribution.setRanges(ranges);
            distribution.setCounts(counts);
            
            logger.info("转换后的分布数据: {}", distribution);
            return distribution;
        } catch (Exception e) {
            logger.error("获取成绩分布数据失败", e);
            return new TeacherScoreAnalysisDTO.ScoreDistribution();
        }
    }
    
    @Override
    public List<TeacherScoreAnalysisDTO.CourseScoreAnalysis> getCourseScoreAnalysis() {
        logger.info("=== 获取教师端课程成绩分析 ===");
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getCourseScoreAnalysis();
            logger.info("数据库查询结果: {}", result);
            
            List<TeacherScoreAnalysisDTO.CourseScoreAnalysis> courseList = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    TeacherScoreAnalysisDTO.CourseScoreAnalysis course = new TeacherScoreAnalysisDTO.CourseScoreAnalysis();
                    course.setCourseName(DataTypeConverter.toString(row.get("courseName")));
                    course.setAverageScore(DataTypeConverter.toBigDecimal(row.get("averageScore")));
                    course.setExamCount(DataTypeConverter.toInteger(row.get("examCount")));
                    course.setStudentCount(DataTypeConverter.toInteger(row.get("studentCount")));
                    courseList.add(course);
                }
            }
            
            logger.info("转换后的课程分析数据: {}", courseList);
            return courseList;
        } catch (Exception e) {
            logger.error("获取课程成绩分析失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<TeacherScoreAnalysisDTO.StudentRanking> getStudentRanking() {
        logger.info("=== 获取教师端学生成绩排名 ===");
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getStudentRanking();
            logger.info("数据库查询结果: {}", result);
            
            List<TeacherScoreAnalysisDTO.StudentRanking> rankingList = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    TeacherScoreAnalysisDTO.StudentRanking ranking = new TeacherScoreAnalysisDTO.StudentRanking();
                    ranking.setStudentId(DataTypeConverter.toString(row.get("studentId")));
                    ranking.setStudentName(DataTypeConverter.toString(row.get("studentName")));
                    ranking.setAverageScore(DataTypeConverter.toBigDecimal(row.get("averageScore")));
                    ranking.setExamCount(DataTypeConverter.toInteger(row.get("examCount")));
                    ranking.setRank(DataTypeConverter.toInteger(row.get("rank")));
                    rankingList.add(ranking);
                }
            }
            
            logger.info("转换后的学生排名数据: {}", rankingList);
            return rankingList;
        } catch (Exception e) {
            logger.error("获取学生成绩排名失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<TeacherScoreAnalysisDTO.ExamRecord> getRecentExamRecords(Integer limit) {
        logger.info("=== 获取教师端最近考试记录 ===");
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getRecentExamRecords(limit);
            logger.info("数据库查询结果: {}", result);
            
            List<TeacherScoreAnalysisDTO.ExamRecord> recordList = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    TeacherScoreAnalysisDTO.ExamRecord record = new TeacherScoreAnalysisDTO.ExamRecord();
                    record.setRecordId(DataTypeConverter.toLong(row.get("recordId")));
                    record.setStudentName(DataTypeConverter.toString(row.get("studentName")));
                    record.setStudentId(DataTypeConverter.toString(row.get("studentId")));
                    record.setExamName(DataTypeConverter.toString(row.get("examName")));
                    record.setCourseName(DataTypeConverter.toString(row.get("courseName")));
                    record.setExamTime(DataTypeConverter.toLocalDateTime(row.get("examTime")));
                    record.setScore(DataTypeConverter.toBigDecimal(row.get("score")));
                    record.setTotalScore(DataTypeConverter.toBigDecimal(row.get("totalScore")));
                    record.setStatus(DataTypeConverter.toString(row.get("status")));
                    recordList.add(record);
                }
            }
            
            logger.info("转换后的最近记录数据: {}", recordList);
            return recordList;
        } catch (Exception e) {
            logger.error("获取最近考试记录失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public TeacherScoreAnalysisDTO.CourseScoreAnalysis getCourseDetailAnalysis(Long courseId) {
        logger.info("=== 获取教师端课程详情分析 ===");
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getCourseDetailAnalysis(courseId);
            logger.info("数据库查询结果: {}", result);
            
            TeacherScoreAnalysisDTO.CourseScoreAnalysis course = new TeacherScoreAnalysisDTO.CourseScoreAnalysis();
            List<BigDecimal> scores = new ArrayList<>();
            List<String> examNames = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    scores.add(DataTypeConverter.toBigDecimal(row.get("averageScore")));
                    examNames.add(DataTypeConverter.toString(row.get("examName")));
                }
            }
            
            course.setScores(scores);
            course.setExamNames(examNames);
            
            logger.info("转换后的课程详情数据: {}", course);
            return course;
        } catch (Exception e) {
            logger.error("获取课程详情分析失败", e);
            return new TeacherScoreAnalysisDTO.CourseScoreAnalysis();
        }
    }
    
    @Override
    public List<TeacherScoreAnalysisDTO.ExamRecord> getExamDetail(Long examId) {
        logger.info("=== 获取教师端考试详情 ===");
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getExamDetail(examId);
            logger.info("数据库查询结果: {}", result);
            
            List<TeacherScoreAnalysisDTO.ExamRecord> recordList = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    TeacherScoreAnalysisDTO.ExamRecord record = new TeacherScoreAnalysisDTO.ExamRecord();
                    record.setRecordId(DataTypeConverter.toLong(row.get("recordId")));
                    record.setStudentName(DataTypeConverter.toString(row.get("studentName")));
                    record.setStudentId(DataTypeConverter.toString(row.get("studentId")));
                    record.setExamName(DataTypeConverter.toString(row.get("examName")));
                    record.setCourseName(DataTypeConverter.toString(row.get("courseName")));
                    record.setExamTime(DataTypeConverter.toLocalDateTime(row.get("examTime")));
                    record.setScore(DataTypeConverter.toBigDecimal(row.get("score")));
                    record.setTotalScore(DataTypeConverter.toBigDecimal(row.get("totalScore")));
                    record.setStatus(DataTypeConverter.toString(row.get("status")));
                    recordList.add(record);
                }
            }
            
            logger.info("转换后的考试详情数据: {}", recordList);
            return recordList;
        } catch (Exception e) {
            logger.error("获取考试详情失败", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 创建空的统计数据
     */
    private TeacherScoreAnalysisDTO.ScoreStatistics createEmptyStatistics() {
        TeacherScoreAnalysisDTO.ScoreStatistics statistics = new TeacherScoreAnalysisDTO.ScoreStatistics();
        statistics.setTotalStudents(0);
        statistics.setTotalExams(0);
        statistics.setAverageScore(BigDecimal.ZERO);
        statistics.setHighestScore(BigDecimal.ZERO);
        statistics.setLowestScore(BigDecimal.ZERO);
        statistics.setPassCount(0);
        statistics.setFailCount(0);
        statistics.setPassRate(BigDecimal.ZERO);
        return statistics;
    }
    
    @Override
    public TeacherScoreAnalysisDTO.ScoreStatistics getScoreStatisticsByCourse(Long courseId) {
        logger.info("=== 获取教师端课程成绩统计数据，课程ID: {} ===", courseId);
        
        try {
            Map<String, Object> result = teacherScoreAnalysisMapper.getScoreStatisticsByCourse(courseId);
            logger.info("数据库查询结果: {}", result);
            
            if (result == null) {
                logger.warn("未查询到课程统计数据");
                return createEmptyStatistics();
            }
            
            TeacherScoreAnalysisDTO.ScoreStatistics statistics = new TeacherScoreAnalysisDTO.ScoreStatistics();
            statistics.setTotalStudents(DataTypeConverter.toInteger(result.get("totalStudents")));
            statistics.setTotalExams(DataTypeConverter.toInteger(result.get("totalExams")));
            statistics.setAverageScore(DataTypeConverter.toBigDecimal(result.get("averageScore")));
            statistics.setHighestScore(DataTypeConverter.toBigDecimal(result.get("highestScore")));
            statistics.setLowestScore(DataTypeConverter.toBigDecimal(result.get("lowestScore")));
            statistics.setPassCount(DataTypeConverter.toInteger(result.get("passCount")));
            statistics.setFailCount(DataTypeConverter.toInteger(result.get("failCount")));
            statistics.setPassRate(DataTypeConverter.toBigDecimal(result.get("passRate")));
            
            logger.info("转换后的课程统计数据: {}", statistics);
            return statistics;
        } catch (Exception e) {
            logger.error("获取课程成绩统计数据失败", e);
            return createEmptyStatistics();
        }
    }
    
    @Override
    public TeacherScoreAnalysisDTO.ScoreTrend getScoreTrendByCourse(Long courseId) {
        logger.info("=== 获取教师端课程成绩趋势数据，课程ID: {} ===", courseId);
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getScoreTrendByCourse(courseId);
            logger.info("数据库查询结果: {}", result);
            
            TeacherScoreAnalysisDTO.ScoreTrend trend = new TeacherScoreAnalysisDTO.ScoreTrend();
            List<String> examDates = new ArrayList<>();
            List<BigDecimal> averageScores = new ArrayList<>();
            List<String> examNames = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    examDates.add(DataTypeConverter.toString(row.get("examDate")));
                    averageScores.add(DataTypeConverter.toBigDecimal(row.get("averageScore")));
                    examNames.add(DataTypeConverter.toString(row.get("examName")));
                }
            }
            
            trend.setExamDates(examDates);
            trend.setAverageScores(averageScores);
            trend.setExamNames(examNames);
            
            logger.info("转换后的课程趋势数据: {}", trend);
            return trend;
        } catch (Exception e) {
            logger.error("获取课程成绩趋势数据失败", e);
            return new TeacherScoreAnalysisDTO.ScoreTrend();
        }
    }
    
    @Override
    public TeacherScoreAnalysisDTO.ScoreDistribution getScoreDistributionByCourse(Long courseId) {
        logger.info("=== 获取教师端课程成绩分布数据，课程ID: {} ===", courseId);
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getScoreDistributionByCourse(courseId);
            logger.info("数据库查询结果: {}", result);
            
            TeacherScoreAnalysisDTO.ScoreDistribution distribution = new TeacherScoreAnalysisDTO.ScoreDistribution();
            List<String> ranges = new ArrayList<>();
            List<Integer> counts = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    ranges.add(DataTypeConverter.toString(row.get("scoreRange")));
                    counts.add(DataTypeConverter.toInteger(row.get("count")));
                }
            }
            
            distribution.setRanges(ranges);
            distribution.setCounts(counts);
            
            logger.info("转换后的课程分布数据: {}", distribution);
            return distribution;
        } catch (Exception e) {
            logger.error("获取课程成绩分布数据失败", e);
            return new TeacherScoreAnalysisDTO.ScoreDistribution();
        }
    }
    
    @Override
    public List<TeacherScoreAnalysisDTO.StudentRanking> getStudentRankingByCourse(Long courseId) {
        logger.info("=== 获取教师端课程学生成绩排名，课程ID: {} ===", courseId);
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getStudentRankingByCourse(courseId);
            logger.info("数据库查询结果: {}", result);
            
            List<TeacherScoreAnalysisDTO.StudentRanking> rankingList = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    TeacherScoreAnalysisDTO.StudentRanking ranking = new TeacherScoreAnalysisDTO.StudentRanking();
                    ranking.setStudentId(DataTypeConverter.toString(row.get("studentId")));
                    ranking.setStudentName(DataTypeConverter.toString(row.get("studentName")));
                    ranking.setAverageScore(DataTypeConverter.toBigDecimal(row.get("averageScore")));
                    ranking.setExamCount(DataTypeConverter.toInteger(row.get("examCount")));
                    ranking.setRank(DataTypeConverter.toInteger(row.get("rank")));
                    rankingList.add(ranking);
                }
            }
            
            logger.info("转换后的课程学生排名数据: {}", rankingList);
            return rankingList;
        } catch (Exception e) {
            logger.error("获取课程学生成绩排名失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<TeacherScoreAnalysisDTO.ExamRecord> getRecentExamRecordsByCourse(Long courseId, Integer limit) {
        logger.info("=== 获取教师端课程最近考试记录，课程ID: {}, 限制数量: {} ===", courseId, limit);
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getRecentExamRecordsByCourse(courseId, limit);
            logger.info("数据库查询结果: {}", result);
            
            List<TeacherScoreAnalysisDTO.ExamRecord> recordList = new ArrayList<>();
            
            if (result != null && !result.isEmpty()) {
                for (Map<String, Object> row : result) {
                    TeacherScoreAnalysisDTO.ExamRecord record = new TeacherScoreAnalysisDTO.ExamRecord();
                    record.setRecordId(DataTypeConverter.toLong(row.get("recordId")));
                    record.setStudentName(DataTypeConverter.toString(row.get("studentName")));
                    record.setStudentId(DataTypeConverter.toString(row.get("studentId")));
                    record.setExamName(DataTypeConverter.toString(row.get("examName")));
                    record.setCourseName(DataTypeConverter.toString(row.get("courseName")));
                    record.setExamTime(DataTypeConverter.toLocalDateTime(row.get("examTime")));
                    record.setScore(DataTypeConverter.toBigDecimal(row.get("score")));
                    record.setTotalScore(DataTypeConverter.toBigDecimal(row.get("totalScore")));
                    record.setStatus(DataTypeConverter.toString(row.get("status")));
                    recordList.add(record);
                }
            }
            
            logger.info("转换后的课程最近记录数据: {}", recordList);
            return recordList;
        } catch (Exception e) {
            logger.error("获取课程最近考试记录失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<Map<String, Object>> getTeacherCourses(String teacherId) {
        logger.info("=== 获取教师课程列表，教师ID: {} ===", teacherId);
        
        try {
            List<Map<String, Object>> result = teacherScoreAnalysisMapper.getTeacherCourses(teacherId);
            logger.info("数据库查询结果: {}", result);
            return result;
        } catch (Exception e) {
            logger.error("获取教师课程列表失败", e);
            return new ArrayList<>();
        }
    }
} 